package com.hzy.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzy.constant.Constants;
import com.hzy.oms.domain.OrderItem;
import com.hzy.oms.domain.OrderOperateHistory;
import com.hzy.oms.domain.bo.OrderCreateBo;
import com.hzy.oms.domain.bo.OrderProductListBo;
import com.hzy.oms.domain.vo.CountOrderVo;
import com.hzy.oms.domain.vo.OrderCalcVO;
import com.hzy.oms.domain.vo.OrderItemVo;
import com.hzy.oms.mapper.OrderItemMapper;
import com.hzy.oms.mapper.OrderOperateHistoryMapper;
import com.hzy.pms.domain.Product;
import com.hzy.pms.domain.Sku;
import com.hzy.pms.domain.bo.ProductBo;
import com.hzy.pms.domain.bo.SkuBo;
import com.hzy.pms.domain.vo.SkuVo;
import com.hzy.pms.mapper.ProductMapper;
import com.hzy.pms.mapper.SkuMapper;
import com.hzy.ums.domain.MemberAddress;
import com.hzy.ums.domain.MemberCart;
import com.hzy.ums.domain.bo.form.OrderSubmitForm;
import com.hzy.ums.domain.vo.MemberVo;
import com.hzy.ums.mapper.MemberAddressMapper;
import com.hzy.ums.mapper.MemberCartMapper;
import com.hzy.ums.mapper.MemberWechatMapper;
import com.hzy.utils.IDGenerator;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hzy.oms.domain.bo.OrderInfoBo;
import com.hzy.oms.domain.vo.OrderInfoVo;
import com.hzy.oms.domain.OrderInfo;
import com.hzy.oms.mapper.OrderInfoMapper;
import com.hzy.oms.service.IOrderInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 订单管理Service业务层处理
 *
 * @author zengxin
 * @date 2023-10-18
 */
@RequiredArgsConstructor
@Service
public class OrderInfoServiceImpl implements IOrderInfoService {

    private final OrderInfoMapper baseMapper;

    private final MemberAddressMapper memberAddressMapper;

    private final SkuMapper skuMapper;

    private final ProductMapper productMapper;

    private final MemberCartMapper memberCartMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderOperateHistoryMapper orderOperateHistoryMapper;

    @Autowired
    private MemberWechatMapper memberWechatMapper;



    /**
     * 查询订单管理
     */
    @Override
    public OrderInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询订单管理列表
     */
    @Override
    public TableDataInfo<OrderInfoVo> queryPageList(OrderInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrderInfo> lqw = buildQueryWrapper(bo);
        Page<OrderInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单管理列表
     */
    @Override
    public List<OrderInfoVo> queryList(OrderInfoBo bo) {
        LambdaQueryWrapper<OrderInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OrderInfo> buildQueryWrapper(OrderInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OrderInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderSn()), OrderInfo::getOrderSn, bo.getOrderSn());
        lqw.eq(bo.getPayId() != null, OrderInfo::getPayId, bo.getPayId());
        lqw.eq(bo.getMemberId() != null, OrderInfo::getMemberId, bo.getMemberId());
        lqw.like(StringUtils.isNotBlank(bo.getMemberUsername()), OrderInfo::getMemberUsername, bo.getMemberUsername());
        lqw.eq(bo.getTotalAmount() != null, OrderInfo::getTotalAmount, bo.getTotalAmount());
        lqw.eq(bo.getPurchasePrice() != null, OrderInfo::getPurchasePrice, bo.getPurchasePrice());
        lqw.eq(bo.getPayAmount() != null, OrderInfo::getPayAmount, bo.getPayAmount());
        lqw.eq(bo.getFreightAmount() != null, OrderInfo::getFreightAmount, bo.getFreightAmount());
        lqw.eq(bo.getPayType() != null, OrderInfo::getPayType, bo.getPayType());
        lqw.eq(bo.getStatus() != null, OrderInfo::getStatus, bo.getStatus());
        lqw.eq(bo.getAftersaleStatus() != null, OrderInfo::getAftersaleStatus, bo.getAftersaleStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliveryCompany()), OrderInfo::getDeliveryCompany, bo.getDeliveryCompany());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliverySn()), OrderInfo::getDeliverySn, bo.getDeliverySn());
        lqw.eq(bo.getAutoConfirmDay() != null, OrderInfo::getAutoConfirmDay, bo.getAutoConfirmDay());
        lqw.like(StringUtils.isNotBlank(bo.getReceiverName()), OrderInfo::getReceiverName, bo.getReceiverName());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverPhone()), OrderInfo::getReceiverPhone, bo.getReceiverPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverPostCode()), OrderInfo::getReceiverPostCode, bo.getReceiverPostCode());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverProvince()), OrderInfo::getReceiverProvince, bo.getReceiverProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverCity()), OrderInfo::getReceiverCity, bo.getReceiverCity());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverDistrict()), OrderInfo::getReceiverDistrict, bo.getReceiverDistrict());
        lqw.eq(bo.getReceiverProvinceId() != null, OrderInfo::getReceiverProvinceId, bo.getReceiverProvinceId());
        lqw.eq(bo.getReceiverCityId() != null, OrderInfo::getReceiverCityId, bo.getReceiverCityId());
        lqw.eq(bo.getReceiverDistrictId() != null, OrderInfo::getReceiverDistrictId, bo.getReceiverDistrictId());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverDetailAddress()), OrderInfo::getReceiverDetailAddress, bo.getReceiverDetailAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getNote()), OrderInfo::getNote, bo.getNote());
        lqw.eq(StringUtils.isNotBlank(bo.getMerchantNote()), OrderInfo::getMerchantNote, bo.getMerchantNote());
        lqw.eq(bo.getConfirmStatus() != null, OrderInfo::getConfirmStatus, bo.getConfirmStatus());
        lqw.eq(bo.getDeleteStatus() != null, OrderInfo::getDeleteStatus, bo.getDeleteStatus());
        lqw.between(params.get("beginPaymentTime") != null && params.get("endPaymentTime") != null,
            OrderInfo::getPaymentTime ,params.get("beginPaymentTime"), params.get("endPaymentTime"));
        lqw.between(params.get("beginDeliveryTime") != null && params.get("endDeliveryTime") != null,
            OrderInfo::getDeliveryTime ,params.get("beginDeliveryTime"), params.get("endDeliveryTime"));
        lqw.between(params.get("beginReceiveTime") != null && params.get("endReceiveTime") != null,
            OrderInfo::getReceiveTime ,params.get("beginReceiveTime"), params.get("endReceiveTime"));
        return lqw;
    }

    /**
     * 新增订单管理
     */
    @Override
    public Boolean insertByBo(OrderInfoBo bo) {
        OrderInfo add = BeanUtil.toBean(bo, OrderInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单管理
     */
    @Override
    public Boolean updateByBo(OrderInfoBo bo) {
        OrderInfo update = BeanUtil.toBean(bo, OrderInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrderInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订单管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional
    public Long submit(OrderSubmitForm form, MemberVo member) {

        //只支持快递
        Long addressId = form.getAddressId();
        if (addressId == null){
            throw new RuntimeException("收获地址不能为空");
        }
        MemberAddress memberAddress = memberAddressMapper.selectById(addressId);
        if (memberAddress == null){
            throw new RuntimeException("收货地址不能为空");
        }
        //sku不能为空
        List<OrderProductListBo> skuList = form.getSkuList();
        if (CollectionUtil.isEmpty(skuList)){
            throw new RuntimeException("商品SKU信息不能为空");
        }
        //将sku信息转换为 key：skuId ，value：购买数量
        Map<Long, Integer> skuQuantityMap = skuList.stream().collect(Collectors.toMap(OrderProductListBo::getSkuId, OrderProductListBo::getQuantity));
        //查询所有sku信息
        Map<Long, Sku> querySkuMap = skuMapper
                .selectBatchIds(skuList.stream().map(OrderProductListBo::getSkuId).collect(Collectors.toList()))
                .stream().collect(Collectors.toMap(Sku::getId, it -> it));
        //计算商品总额、订单总额（订单总金额=商品总金额，因为暂时没有运费等概念）
        BigDecimal productTotalAmount = BigDecimal.ZERO;
        BigDecimal orderTotalAmount = BigDecimal.ZERO;
        for (OrderProductListBo dto : skuList){
            if (!querySkuMap.containsKey(dto.getSkuId())){
                throw new RuntimeException("商品SKU不存在");
            }
            Sku sku = querySkuMap.get(dto.getSkuId());
            Product product = productMapper.selectById(sku.getProductId());
            if (product == null){
                throw new RuntimeException("商品不存在");
            }
            if (Constants.PublishStatus.UNDERCARRIAGE.equals(product.getPublishStatus())){
                throw new RuntimeException("商品" + product.getName() + "已下架");
            }
            if (sku.getStock() < skuQuantityMap.get(sku.getId())) {
                throw new RuntimeException("库存不足");
            }
            productTotalAmount = productTotalAmount.add(sku.getPrice().multiply(BigDecimal.valueOf(skuQuantityMap.get(sku.getId()))));
            orderTotalAmount = orderTotalAmount.add(sku.getPrice().multiply(BigDecimal.valueOf(skuQuantityMap.get(sku.getId()))));
            dto.setSku(BeanUtil.toBean(sku, SkuBo.class));
            dto.setProduct(BeanUtil.toBean(product, ProductBo.class));
        }
        Date optTime = new Date();

        //生成一个统一的订单号
        Long orderId = IDGenerator.generateId();
        //生产一个payId
        Long payId = IDGenerator.generateId();
        //创建订单
        OrderInfo order = new OrderInfo();
        order.setPayId(payId);
        order.setId(orderId);
        order.setOrderSn(this.getOrderIdPrefix() + orderId);
        order.setMemberId(member.getId());
        order.setMemberUsername(member.getNickname());
        order.setPayType(Constants.PayType.WECHAT);
        order.setTotalAmount(orderTotalAmount);
        order.setPurchasePrice(BigDecimal.ZERO);
        order.setFreightAmount(BigDecimal.ZERO);
        order.setPayAmount(orderTotalAmount);
        order.setStatus(Constants.OrderStatus.NOTPAID);
        order.setAftersaleStatus(1);
        order.setReceiverName(memberAddress.getName());
        order.setReceiverPhone(memberAddress.getPhoneHidden());
        order.setReceiverPostCode(memberAddress.getPostCode());
        order.setReceiverProvince(memberAddress.getProvince());
        order.setReceiverCity(memberAddress.getCity());
        order.setReceiverDistrict(memberAddress.getDistrict());
        order.setReceiverProvinceId(memberAddress.getProvinceId());
        order.setReceiverCityId(memberAddress.getCityId());
        order.setReceiverDistrictId(memberAddress.getDistrictId());
        order.setReceiverDetailAddress(memberAddress.getDetailAddress());
        order.setNote(form.getNote());
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
//        order.setPaymentTime(optTime);
        order.setCreateTime(optTime);
        order.setCreateBy(member.getId().toString());
        int rows = baseMapper.insert(order);
        if (rows < 1){
            throw new RuntimeException("订单新增失败");
        }
        // 保存orderItem
        List<OrderItem> addOrderItemList = new ArrayList<>();
        skuList.forEach(item -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setId(IDGenerator.generateId());
            orderItem.setOrderId(orderId);
            orderItem.setProductId(item.getProduct().getId());
            orderItem.setOutProductId(item.getProduct().getOutProductId());
            orderItem.setSkuId(item.getSku().getId());
            orderItem.setOutSkuId(item.getSku().getOutSkuId());
            orderItem.setPic(item.getSku().getPic());
            orderItem.setProductName(item.getProduct().getName());
            orderItem.setSalePrice(item.getSku().getPrice());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setProductCategoryId(item.getProduct().getCategoryId());
            orderItem.setSpData(item.getSku().getSpData());
            orderItem.setCreateBy(member.getId().toString());
            orderItem.setCreateTime(optTime);
            addOrderItemList.add(orderItem);
            //减少sku的库存
            skuMapper.updateStockById(item.getSkuId(), optTime,item.getQuantity());
        });
        boolean flag = orderItemMapper.insertBatch(addOrderItemList);
        if (!flag){
            throw new RuntimeException("新增订单item失败");
        }

//        skuList.forEach(item -> {
//            //减少sku的库存
//            skuMapper.updateStockById(item.getSkuId(),LocalDateTime.now(),item.getQuantity());
//        });
        // 保存订单操作记录
        OrderOperateHistory orderOperateHistory = new OrderOperateHistory();
        orderOperateHistory.setOrderId(orderId);
        orderOperateHistory.setOrderSn(order.getOrderSn());
        orderOperateHistory.setOperateMan(member.getId() + "");
        orderOperateHistory.setOrderStatus(Constants.OrderStatus.NOTPAID);
        orderOperateHistory.setCreateTime(optTime);
        orderOperateHistory.setCreateBy(member.getId().toString());
        rows = orderOperateHistoryMapper.insert(orderOperateHistory);
        if (rows < 1){
            throw new RuntimeException("保存订单操作记录失败");
        }
        //若来源为购物车，删除购物车
        if (Constants.OrderFrom.CART.equals(form.getFrom())){
            List<Long> skuIdList = skuList.stream().map(OrderProductListBo::getSkuId).collect(Collectors.toList());
            LambdaUpdateWrapper<MemberCart> wrapper = Wrappers.lambdaUpdate();
            wrapper.eq(MemberCart::getMemberId, member.getId());
            wrapper.in(MemberCart::getSkuId, skuIdList);
            rows = memberCartMapper.delete(wrapper);
            if (rows < 1){
                throw new RuntimeException("删除购物车失败");
            }
        }
        //当前订单id，接入支付后可返回payId
        return payId;
    }

    private String getOrderIdPrefix(){
        LocalDateTime time = LocalDateTime.now();
        return time.format(DateTimeFormatter.ofPattern("yyMMdd")) + "-";
    }

    @Override
    public OrderCalcVO addOrderCheck(OrderCreateBo bo) {
        OrderCalcVO res = new OrderCalcVO();
        List<SkuVo> skuList = new ArrayList<>();
        List<OrderProductListBo> list = bo.getSkuList();
        if (CollectionUtil.isEmpty(list)){
            throw new RuntimeException("商品SKU信息不能为空");
        }
        //将购买的sku信息转化为key：skuId value：数量
        Map<Long, Integer> quantityMap = list.stream().
                collect(Collectors.toMap(OrderProductListBo::getSkuId, OrderProductListBo::getQuantity, (v1, v2) -> v2));
        //查询所有sku信息
        Set<Long> collect = list.stream().map(OrderProductListBo::getSkuId).collect(Collectors.toSet());
        Map<Long, Sku> querySkuMap = skuMapper.selectBatchIds(collect).stream().collect(Collectors.toMap(Sku::getId, it -> it));
        //计算商品总金额、订单总金额
        BigDecimal productTotalAmount = BigDecimal.ZERO;
        BigDecimal orderTotalAmount = BigDecimal.ZERO;
        for (OrderProductListBo dto : list){
            if (!querySkuMap.containsKey(dto.getSkuId())){
                throw new RuntimeException("商品SKU不存在");
            }
            Sku sku = querySkuMap.get(dto.getSkuId());
            //查product
            Product product = productMapper.selectById(sku.getProductId());
            if (product == null){
                throw new RuntimeException("商品不存在");
            }
            if (Constants.PublishStatus.UNDERCARRIAGE.equals(product.getPublishStatus())){
                throw new RuntimeException("商品" + product.getName() + "已下架");
            }
            if (sku.getStock() < quantityMap.get(sku.getId())) {
                throw new RuntimeException("库存不足");
            }
            BigDecimal addAmount = sku.getPrice().multiply(BigDecimal.valueOf(dto.getQuantity()));
            //由于目前没有运费等数据，暂时订单总金额=商品总金额了
            productTotalAmount = productTotalAmount.add(addAmount);
            orderTotalAmount = orderTotalAmount.add(addAmount);
            //封装sku信息
            SkuVo skuViewDTO = new SkuVo();
            skuViewDTO.setPic(product.getPic());
            skuViewDTO.setPrice(sku.getPrice());
            skuViewDTO.setProductId(product.getId());
            skuViewDTO.setProductName(product.getName());
            skuViewDTO.setQuantity(quantityMap.get(sku.getId()));
            skuViewDTO.setSkuId(sku.getId());
            skuViewDTO.setSpData(sku.getSpData());
            skuList.add(skuViewDTO);
        }
        res.setSkuList(skuList);
        res.setOrderTotalAmount(orderTotalAmount);
        res.setProductTotalAmount(productTotalAmount);
        return res;
    }

    @Override
    public TableDataInfo<OrderInfoVo> orderPage(OrderInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrderInfo> lqw = buildQueryWrapper(bo);
        Page<OrderInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<Long> idList = result.getRecords().stream().map(OrderInfoVo::getId).collect(Collectors.toList());
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.in("order_id", idList);
        Map<Long, List<OrderItem>> orderItemMap =
                orderItemMapper.selectList(orderItemQw).stream().collect(Collectors.groupingBy(OrderItem::getOrderId));

        return TableDataInfo.build(result);
    }

    @Override
    public OrderInfoVo orderDetail(Long orderId) {
        OrderInfoVo order = baseMapper.selectVoById(orderId);
        if (order == null){
            throw new RuntimeException("未查询到该订单");
        }
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", orderId);
        List<OrderItemVo> orderItemList = orderItemMapper.selectVoList(orderItemQw);
        order.setOrderItemList(orderItemList);
        // 如果未付款，计算倒计时
        if (Constants.OrderStatus.NOTPAID.equals(order.getStatus())){
            // 订单超时时间900s，后面可以配置到字典等
            Integer time = 900;
            Date addDate = DateUtils.addSeconds(order.getCreateTime(), time);
            if (order.getCreateTime().after(new Date())) {
                order.setTimeToPay(order.getCreateTime().getTime());
            }
        }
        return order;
    }

    @Override
    @Transactional
    public String orderComplete(Long orderId) {
        Date optDate = new Date();
        OrderInfo order = baseMapper.selectById(orderId);
        OrderItem queryOrderItem = new OrderItem();
        queryOrderItem.setOrderId(orderId);
        QueryWrapper<OrderItem> orderItemQw = new QueryWrapper<>();
        orderItemQw.eq("order_id", orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemQw);
        if(order == null || CollectionUtil.isEmpty(orderItemList)){
            throw new RuntimeException("未查询到订单信息");
        }
        // 只有【待收货】状态才能确认
        if(!order.getStatus().equals(Constants.H5OrderStatus.DELIVERED)){
            throw new RuntimeException("订单状态已改变，请刷新");
        }
        //更新订单
        UpdateWrapper<OrderInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", order.getId());
        updateWrapper.set("status", Constants.H5OrderStatus.COMPLETED);
        updateWrapper.set("confirm_status", 1);
        updateWrapper.set("receive_time", optDate);
        int rows = baseMapper.update(null, updateWrapper);
        if (rows < 1){
            throw new RuntimeException("更新订单状态失败");
        }
        //创建订单操作记录
        OrderOperateHistory optHistory = new OrderOperateHistory();
        optHistory.setOrderId(order.getId());
        optHistory.setOrderSn(order.getOrderSn());
        optHistory.setOperateMan("" + order.getMemberId());
        optHistory.setOrderStatus(Constants.H5OrderStatus.COMPLETED);
        optHistory.setCreateTime(optDate);
        optHistory.setCreateBy(order.getMemberId().toString());
        optHistory.setUpdateBy(order.getMemberId().toString());
        optHistory.setUpdateTime(optDate);
        rows = orderOperateHistoryMapper.insert(optHistory);
        if (rows < 1){
            throw new RuntimeException("创建订单操作记录失败");
        }
        return order.getOrderSn();
    }

    /**
     * 统计待付款、待发货、待收货和售后订单数量
     * @param memberId
     * @return
     */
    public CountOrderVo orderNumCount(Long memberId) {
        return  baseMapper.countByStatusAndMemberId(memberId);
    }

    @Override
    public String orderBatchCancel(List<Long> idList, Long userId) {
        Date optDate = new Date();
        if (CollectionUtil.isEmpty(idList)){
            throw new RuntimeException("未指定需要取消的订单号");
        }
        List<OrderInfo> orderList = baseMapper.selectList(new LambdaQueryWrapper<OrderInfo>().in(OrderInfo::getId, idList));
        if (orderList.size() < idList.size()){
            throw new RuntimeException("未查询到订单信息");
        }
        //查orderItem
        QueryWrapper<OrderItem> qw = new QueryWrapper<>();
        qw.in("order_id", idList);
        List<OrderItem> orderItem = orderItemMapper.selectList(qw);
        if (CollectionUtil.isEmpty(orderItem)) {
            throw new RuntimeException("未查询到订单信息");
        }
        long count = orderList.stream().filter(it -> !Constants.H5OrderStatus.UN_PAY.equals(it.getStatus())).count();
        if (count > 0){
            throw new RuntimeException("订单状态已更新，请刷新页面");
        }
        List<OrderOperateHistory> addHistoryList = new ArrayList<>();
        orderList.forEach(item -> {
            item.setStatus(Constants.H5OrderStatus.CLOSED);
            item.setUpdateTime(optDate);
            item.setUpdateBy(userId.toString());
            OrderOperateHistory history = new OrderOperateHistory();
            history.setOrderId(item.getId());
            history.setOrderSn(item.getOrderSn());
            history.setOperateMan(userId == null ? "后台管理员" : "" + item.getMemberId());
            history.setOrderStatus(Constants.H5OrderStatus.CLOSED);
            history.setCreateTime(optDate);
            history.setCreateBy(userId.toString());
            history.setUpdateBy(userId.toString());
            history.setUpdateTime(optDate);
            addHistoryList.add(history);

        });
//        //取消订单
//        int rows = baseMapper.update(null, new LambdaUpdateWrapper<OrderInfoVo>()
//                .set(OrderInfoVo::getStatus, Constants.H5OrderStatus.CLOSED)
//                .set(OrderInfoVo::getUpdateTime, optDate)
//                .set(OrderInfoVo::getUpdateBy, userId.toString())
//                .in(OrderInfoVo::getId, idList));
        //        if (rows < 1){
//            throw new RuntimeException("更改订单状态失败");
//        }
        boolean b = baseMapper.updateBatchById(orderList);
        if(b){
            throw new RuntimeException("更改订单状态失败");
        }

        orderItem.stream().collect(Collectors.groupingBy(it->it.getSkuId())).forEach((k,v)->{
            AtomicReference<Integer> totalCount = new AtomicReference<>(0);
            v.forEach(it-> totalCount.updateAndGet(v1 -> v1 + it.getQuantity()));
            skuMapper.updateStockById(k, optDate, -1 * totalCount.get());
        });

        //创建订单操作记录
        boolean flag = orderOperateHistoryMapper.insertBatch(addHistoryList);
        if (!flag){
            throw new RuntimeException("创建订单操作记录失败");
        }
        return "取消订单成功";
    }
}
